package com.tuozixuan;

import static com.tuozixuan.GitDemoConstants.LOCAL_DIR;
import static com.tuozixuan.GitDemoConstants.USERNAME;

import java.io.File;

import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.revwalk.RevCommit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GitCommitDemo {
	
	private static Logger logger = LoggerFactory.getLogger(GitCommitDemo.class);

	public static void main(String[] args) throws Exception {

		Git git = Git.open(new File(LOCAL_DIR));
		Status status = git.status().call();
		String commitId = null;
		if (!status.isClean()) {
			// 执行 git 提交
			git.add().addFilepattern(".").call();
			logger.info("Git add all files success.");
			CommitCommand commit = git.commit();
			// 指定用户提交
			String comment = "test git add";
			RevCommit call = commit.setMessage(comment).setCommitter(USERNAME, "tuozixuan@github.com").call();
			commitId = call.getName();
		} else {
			logger.info("Git status is clean,nothing to commit.");
			Iterable<RevCommit> call = git.log().setMaxCount(1).call();
			for (RevCommit revCommit : call) {
				commitId = revCommit.getName();
			}
		}
		logger.info("commitId:{}", commitId);
	}

}
